package com.wxxymakers.cklabrecruit.service;

import com.wxxymakers.cklabrecruit.entity.User;
import com.wxxymakers.cklabrecruit.entity.UserExample;
import com.wxxymakers.cklabrecruit.mapper.UserMapper;
import com.wxxymakers.cklabrecruit.utils.DateUtils;
import com.wxxymakers.cklabrecruit.utils.PageUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @AUTHOR soft
 * @DATE 2018/11/5 22:11
 * @DESCRIBE 用户业务层
 */
@Service
public class UserService implements IService<User> {

    private final UserMapper mapper;

    @Autowired
    public UserService(UserMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    @Transactional
    public User add(User user) {
        Md5Hash hash     = new Md5Hash(user.getPassword(), user.getUsername(), 101);
        String  basePass = hash.toHex();
        user.setPassword(basePass);
        user.setDatetime(new Date());
        int id = mapper.insertSelective(user);
        if (id > 0) {
            return user;
        }
        return null;
    }

    @Override
    @Transactional
    public User delete(Object id) {
        User one = getOne(id);
        if (one != null) {
            if (mapper.deleteByPrimaryKey(one.getId()) > 0) {
                return one;
            }
        }
        return null;
    }

    @Override
    @Transactional
    public boolean change(User entity) {
        return mapper.updateByPrimaryKeySelective(entity) > 0;
    }

    @Override
    public User getOne(Object id) {
        return mapper.selectByPrimaryKey((Integer) id);
    }

    @Override
    public Page<User> getPage(int pageNo, int size, User entity) {
        UserExample example = new UserExample();
        example.setLimit(size);
        example.setOffset((pageNo - 1) * size);
        example.setOrderByClause("id desc");
        if (entity != null) {
            UserExample.Criteria criteria = example.createCriteria();
            if (entity.getRole() != null) {
                criteria.andRoleEqualTo(String.valueOf(entity.getRole().ordinal()));
            }

            if (!StringUtils.isEmpty(entity.getDatetime())) {
                Date[] between = DateUtils.getBetween(entity.getDatetime());
                criteria.andDatetimeBetween(between[0], between[1]);
            }
        }
        List<User> users = mapper.selectByExample(example);
        if (CollectionUtils.isEmpty(users)) return null;
        long       total = mapper.countByExample(example);
        return PageUtils.page(users, pageNo, size, total);
    }

    public User getByUsername(String username) {
        return mapper.selectByUsername(username);
    }
}
